<template>
    <div class="tree-select">
        <el-tree-select v-model="deptId" placeholder="请选择所属部门" :data="treeData" filterable clearable
            style="width: 200px;" @change="changeSelect" :props="{ value: 'id', label: 'name', children: 'children' }"
            check-strictly default-expand-all>
            <template #default="{ data: { name,dictDeptType} }">
                <div style="display: flex;">
                    <div style="margin-right: 8px;">
                        <svg-icon v-if="dictDeptType === '1'" name="headoffice" width="18px" height="18px"
                            color=var(--el-text-color-regular)></svg-icon>
                        <svg-icon v-if="dictDeptType === '2'" name="branchoffice" width="18px" height="18px" 
                            color=var(--el-text-color-regular)></svg-icon>
                        <svg-icon v-if="dictDeptType === '3'" name="department" width="18px" height="18px"
                            color=var(--el-text-color-regular)></svg-icon>
                    </div>
                    {{name}}
                </div>
            </template>
        </el-tree-select>
    </div>
</template>
<script setup lang="ts">
import pubApi from '@/api/pub';
interface TreeNode {
    id: number;
    parentId: number;
    name: string;
    children?: TreeNode[];
    dictDeptType: string;
}

const treeData = ref<TreeNode[]>([]);
const deptId = ref('');
const deptLoading = ref(false);
const getDeptList = async () => {
    try {
        deptLoading.value = true;
        let results = await pubApi.getDeptList({
            "dictDeptType": null,
            "dictDeptStatus": '1',
        }) as any;
        if (results) {
            deptLoading.value = false;
            // 接口调用成功
            treeData.value = results
        } else {
            deptLoading.value = false;
            // 处理接口调用成功，但返回结果为空的情况
            throw new Error("接口调用成功，但返回结果为空");
        }
    } catch (error) {
        // 处理接口调用失败的情况
        throw new Error("接口调用失败"); // 返回一个默认值或者进行其他错误处理
    }
};
const $emit = defineEmits(["update:modelValue", 'change']);
const changeSelect = () => {
    $emit("update:modelValue", deptId.value);
    $emit('change', deptId.value);
};

onMounted(() => {
    getDeptList();
});
</script>
<style scoped>
.tree-select {
    display: inline-block;
}
</style>